package com.emptyMe.org.service.imp;

import com.emptyMe.basic.utils.AjaxResult;
import com.emptyMe.basic.utils.Constant;
import com.emptyMe.basic.utils.MD5Utils;
import com.emptyMe.org.domain.LoginInfo;
import com.emptyMe.org.domain.LoginInfoDTO;
import com.emptyMe.org.domain.Menu;
import com.emptyMe.org.mapper.LoginInfoMapper;
import com.emptyMe.org.service.ILoginInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class LoginInfoServiceImpl implements ILoginInfoService {
    @Autowired
    private LoginInfoMapper mapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public LoginInfoDTO login(LoginInfo info) {
        LoginInfo user = mapper.findByUserOrPhoneOrEmail(info);
        if (user == null) {
            // 用户名不存在
            throw new RuntimeException("用户名或密码错误");
        } else {
            // 比较密码
            if (Objects.equals(MD5Utils.encrypByMd5(info.getPassword() + Constant.PRE_SALT + user.getSalt() + Constant.END_SALT), user.getPassword())){
                // 密码对上了
                // 响应token 颁发令牌
                String uuid = UUID.randomUUID().toString();
                redisTemplate.opsForValue().set(uuid,user.getUsername(),30, TimeUnit.MINUTES);
                LoginInfoDTO dto = new LoginInfoDTO();
                dto.setUsername(info.getUsername());
                dto.setType(user.getType());
                dto.setToken(uuid);
                dto.setId(user.getId());
                return dto;
            }else {
                // 密码错误
                throw new RuntimeException("用户名或密码错误");
            }

//            // 区分是管理员还是普通用户
//            if (user.getType() == 0) {
//                // 管理员登陆
//            } else {
//                // 普通用户登录
//            }
        }
    }

    @Override
    public AjaxResult menuList(Long id) {
        Menu menu =  mapper.menuList(id);
        return AjaxResult.me(menu);
//        ArrayList<Map<String, Object>> list = new ArrayList<>();
//        HashMap<String, Object> map = new HashMap<>();
//        list.add(map);
//        map = new HashMap<>();
//        map.put( "path","/"+menu.getName());
//        map.put("name", menu.getName());
//        ArrayList<Map<String, Object>> list2 = new ArrayList<>();
//        HashMap<String, Object> map2 = new HashMap<>();
//        map2.put("path", "dept");
//        map2.put("name", "Dept");
//        list2.add(map2);
//        map.put("children",list2);
//
//        list.add(map);
//        dto.setMenuList(list);
    }
}
